/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState, useEffect } from 'react';
import { message, Space, Button, Popconfirm } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import ProForm, { ProFormSelect, ProFormText } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import KbAddCustomersModal from './compinents/KbAddCustomersModal/';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ConnectState } from '@/models/connect';
import type { CustomersItem } from '../index.d';
import {
  getCustomersList,
  getDeliveryAccountList,
  removeCustomers,
  getAccountCityList,
} from '@/services/jdk/customers';
import { customersColumns } from '@/components/_pages/jdk/index.config';
import { useSelector } from 'umi';
import styles from './index.less';

const Index = ({ show }: { show: boolean }) => {
  const actionRef = useRef<ActionType>();
  const [record, setRecord] = useState<any>();
  const [visible, setVisible] = useState<boolean>(false);
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const proFormRef = useRef<ProFormInstance>();
  const [formData, setFormData] = useState<any>();

  const onClose = () => {
    setVisible(false);
    setRecord({});
  };
  const handelAddCustomers = () => setVisible(true);

  const handleModify = (record_: any) => {
    const { shop_cate_ids = '' } = record_ || {};
    setRecord({ shop_cate_ids: shop_cate_ids ? shop_cate_ids.split(',') : [], ...record_ });
    handelAddCustomers();
  };

  const handleRemove = async (record_: CustomersItem) => {
    const { user_id } = record_;
    const { code, msg } = await removeCustomers({ user_id });
    if (code == 0) {
      message.success(msg);
      actionRef.current?.reload();
    } else {
      message.error(msg);
    }
  };

  const optionColumns: ProColumns<CustomersItem>[] = [
    {
      title: '操作',
      valueType: 'option',
      width: winSize === 'xs' ? 50 : 80,
      align: 'center',
      fixed: 'right',
      render: (_, item) => {
        return (
          <Space direction='vertical'>
            <a onClick={handleModify.bind(null, item)}>编辑</a>
            <Popconfirm title='你确定移除吗？' onConfirm={handleRemove.bind(null, item)}>
              <a>移除</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  const queryTable = async (values: any) => {
    const { current: page, pageSize: size } = values;
    const { code, data, msg } = await getCustomersList({ page, size, ...formData });
    const list = data.list.map((item: any, index: number) => ({
      ...item,
      id: index + 1,
    }));
    if (code == 0) {
      return {
        data: list,
        total: data.total,
      };
    } else {
      message.error(msg);
      return {};
    }
  };
  const onProFormSubmit = async (values: any) => {
    setFormData(values);
    actionRef.current?.reload(true);
  };
  useEffect(() => {
    if (show) actionRef.current?.reload();
  }, [show]);
  return (
    <PageContainer className={styles.main}>
      <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
        <ProForm
          formRef={proFormRef}
          layout='inline'
          onFinish={onProFormSubmit}
          initialValues={{
            brand: 'gxd',
            city: '遂宁市',
          }}
          submitter={{
            render: (form_props) => {
              return [
                <Button
                  key='reset'
                  onClick={() => {
                    form_props.form?.resetFields();
                    form_props.form?.submit?.();
                  }}
                >
                  重置
                </Button>,
                <Button type='primary' key='submit' onClick={() => form_props.form?.submit?.()}>
                  查询
                </Button>,
                <Button key='add' type='primary' onClick={handelAddCustomers}>
                  添加大客户
                </Button>,
              ];
            },
          }}
        >
          <ProFormSelect
            name='brand'
            label='运力品牌'
            placeholder='请选择运力品牌'
            fieldProps={{
              allowClear: false,
              style: { width: '120px' },
            }}
            valueEnum={{
              gxd: '裹小递',
            }}
          />
          <ProFormSelect
            name='city'
            label='所在城市'
            showSearch
            fieldProps={{
              placeholder: '请选择城市',
              allowClear: false,
            }}
            valueEnum={{
              gxd: '遂宁市',
            }}
            request={getAccountCityList}
            rules={[{ required: true, message: '请选择城市' }]}
          />
          <ProFormSelect
            name='auth_id'
            label='运力账号'
            placeholder='请选择运力账号'
            dependencies={['city']}
            fieldProps={{
              allowClear: false,
              style: { width: '160px' },
            }}
            request={() => {
              const city = proFormRef.current?.getFieldsValue(['city']) || { city: '遂宁市' };
              return getDeliveryAccountList(city);
            }}
            rules={[{ required: true, message: '请选择运力账号' }]}
          />
          <ProFormText name='user_phone' placeholder='输入账号查询' />
        </ProForm>
      </Space>
      <DragTable>
        <ProTable
          rowKey='id'
          actionRef={actionRef}
          request={queryTable}
          columns={[...customersColumns, ...optionColumns]}
          search={false}
          toolBarRender={false}
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          scroll={{
            x: 1200,
          }}
        />
      </DragTable>
      <KbAddCustomersModal
        visible={visible}
        onClose={onClose}
        record={record}
        actionRef={actionRef}
      />
    </PageContainer>
  );
};

export default Index;
